package pers.leeyns.cms.ui.commons;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.io.ByteStreams;

import net.coobird.thumbnailator.Thumbnails;
import pers.leeyns.cms.cache.EHCache;

public class ImageResources {
	private static Logger log = LoggerFactory.getLogger(ImageResources.class);
	private static EHCache ehCache = new EHCache();
	
	public static  BufferedImage thumbImages(String filename){
		try {
			return Thumbnails.of(filename).size(800, 600).keepAspectRatio(true).asBufferedImages().get(0);
		} catch (IOException e) {
			return null;
		}
	}
	
	public static  BufferedImage thumbImages(BufferedImage buff){
		try {
			return Thumbnails.of(buff).size(1000, 1000).asBufferedImages().get(0);
		} catch (IOException e) {
			return null;
		}
	}
	
	static {
		loadImageIcons();
	}
	
	public static void loadImageIcons(){
		 try {
			ehCache.add(ImgKey.IMG_KEY_FRAME_BACKGROUND,getImageBytes("/images/bg-06.jpg"));
		 } catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static byte[] getImageBytes(String file){
		try {
			return ByteStreams.toByteArray(Thread.currentThread().getClass().getResourceAsStream(file));
		} catch (IOException e) {
			log.error("Read image failed.");
			return null;
		}
	}
	
	public static byte[] getCacheImageBytes(String key){
		try {
			return (byte[]) ehCache.get(key);
		} catch (Exception e) {
			log.error("Get image  exception:key={}",key,e);
			return null;
		}
	}
	public static Image getImage(String key){
		try {
			byte[] bytes = getCacheImageBytes(key);
			return new ImageIcon(bytes).getImage();
		} catch (Exception e) {
			log.error("Get image icon exception:key={}",key,e);
			return null;
		}
	}
	public static ImageIcon getImageIcon(String key){
		try {
			byte[] bytes = getCacheImageBytes(key);
			return new ImageIcon(bytes);
		} catch (Exception e) {
			log.error("Get image icon exception:key={}",key,e);
			return null;
		}
	}
	
	public static class ImgKey{
		public static final String IMG_KEY_FRAME_BACKGROUND = "img.key.frame.background";
	}
}
